package browser
{
	import caurina.transitions.Tweener;
	
	import datas.GlobalDatas;
	
	import events.GlobalEvents;
	
	import fileloader.ListFile;
	
	import flash.display.Sprite;
	import flash.events.Event;
	
	import uiobj.ListThumb;

	public class list extends Sprite
	{
		private var stagewidth:int;
		private var imgArr:Array = new Array;
		private var display:Boolean = true;
		
		public function list()
		{
			listFiles();
		}
		
		private function addEvents():void
		{
			trace("addEvents()");
			GlobalEvents.dispatcher.addEventListener(GlobalEvents.STAGE_RESIZED, onStageResize);
			GlobalEvents.dispatcher.addEventListener(GlobalEvents.VIEW_LIST, onListView);
			GlobalEvents.dispatcher.addEventListener(GlobalEvents.HIDE_LIST, onHideView);
		}
		
		private function listFiles():void
		{
			stagewidth = GlobalDatas.stagewidth;
			
			var listfile:ListFile = new ListFile;
			listfile.addEventListener(ListFile.FILE_LIST_COMPLETE, onListComplete);
			listfile.load();
		}
		
		private function onListComplete(e:Event):void
		{
			var xml:XML = e.target.data;
			var i:int = 0;
			var col:int = 0;
			for each(var data:XML in xml.item)
			{
				var row:int = stagewidth / (GlobalDatas.THUMB_SIZE + GlobalDatas.THUMB_MARGIN);
				var thum:ListThumb = new ListThumb;
				thum.load(data);
				thum.x = (i % row) * (GlobalDatas.THUMB_SIZE + GlobalDatas.THUMB_MARGIN);
				
				if(i > 0 && (i%row) == 0)
					col++;
				thum.y = col * (GlobalDatas.THUMB_SIZE + GlobalDatas.THUMB_MARGIN);
				addChild(thum);
				imgArr.push(thum);
				i++;
			}
			showList();
			this.width = row * (GlobalDatas.THUMB_SIZE + GlobalDatas.THUMB_MARGIN);
			listViewPosttion();
			addEvents();
		}
		
		private function showList():void
		{
			var row:int = stagewidth / (GlobalDatas.THUMB_SIZE + GlobalDatas.THUMB_MARGIN);
			var col:int = 0;
			for(var i:int = 0 ; i < imgArr.length ; i++)
			{
				imgArr[i].x = (i % row) * (GlobalDatas.THUMB_SIZE + GlobalDatas.THUMB_MARGIN);
				if(i > 0 && (i%row) == 0)
					col++;
				imgArr[i].y = col * (GlobalDatas.THUMB_SIZE + GlobalDatas.THUMB_MARGIN);
			}
		}
		
		private function onStageResize(e:Event):void
		{
			trace("onStageResize");
			stagewidth = GlobalDatas.stagewidth;
			showList();
			listViewPosttion();
		}
		
		private function onHideView(e:Event):void
		{
			trace("onHideView()");
			display = false;
			listViewPosttion();
		}
		
		private function onListView(e:Event):void
		{
			display = true;
			listViewPosttion();
		}
		
		private function listViewPosttion():void
		{
			trace(display);
			if(display == true)
				Tweener.addTween(this,{x:(GlobalDatas.stagewidth-this.width)/2,time:1});
			else
				Tweener.addTween(this,{x:0-this.width,time:1});
		}
	}
}